﻿using System.Collections;
using System.Collections.Generic;
using TinyTeam.UI;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;

public class TipUI : TTUIPage
{
    private Text text;
    private Image image;
    private RectTransform rtt;
    private RectTransform rti;
    private TipUIData uiData;
    private Coroutine ct;
    public static bool isShowing;
    private Tweener tw1;
    private Tweener tw2;
    private Tweener tw3;
    private Tweener tw4;

    public TipUI() : base(UIType.PopUp, UIMode.DoNothing, UICollider.None)
    {
        uiPath = "UI/TipUI";
    }

    public override void Awake(GameObject go)
    {
        text = go.transform.Find("Image/Text").GetComponent<Text>();
        image = go.transform.Find("Image").GetComponent<Image>();
        rtt = text.GetComponent<RectTransform>();
        rti = image.GetComponent<RectTransform>();
    }

    public override void Hide()
    {
        tw1 = text.DOFade(1f, 2f);
        tw2 = image.DOFade(1f, 2f).OnComplete(() =>
        {
            tw3 = text.DOFade(0f, 1f);
            tw4 = image.DOFade(0f, 1f).OnComplete(() =>
            {
                base.Hide();
                isShowing = false;
                uiData.cb?.Invoke();
            });
        });
    }

    public override void Refresh()
    {
        if (isShowing)
        {
            Debug.Log("return");
            return;
        }

        isShowing = true;
        uiData = (TipUIData) data;

        tw1?.Kill();
        tw2?.Kill();
        tw3?.Kill();
        tw4?.Kill();

        text.color = Color.black;
        image.color = Color.white;
        text.text = "";
        int size = 0;
        text.font.RequestCharactersInTexture(uiData.content, text.fontSize, text.fontStyle);
        CharacterInfo ci;
        for (int k = 0; k < uiData.content.Length; k++)
        {
            text.font.GetCharacterInfo(uiData.content[k], out ci, text.fontSize);
            size += ci.advance;
        }

        size = Mathf.Clamp(size, 500, 1920);
        rtt.sizeDelta = new Vector2(size + 4, rtt.sizeDelta.y);
        rti.sizeDelta = new Vector2(size + 100, rti.sizeDelta.y);

        if (ct != null)
        {
            Util.instance.StopCoroutine(ct);
        }

        Debug.Log(uiData.content);
        ct = Util.instance.Typewriter(uiData.content, 0.05f, text, () => { ClosePage<TipUI>(); });
    }
}